export default{
    namespaced: true,
    state: {
        cartData:[]    
    }, 
    mutations: {
        SET_CART(state,payload){
            // state.cartData = payload

            let target = state.cartData.find(item=>item.id===payload.id)

            // 没有
            if(!target){
                // 重新定义购物车数据
                let obj = {
                    title:payload.title,
                    price:payload.price,
                    count:1,
                    id:payload.id
                }
                state.cartData.push(obj)
            }else{
                // 有
                console.log(target);
                target.count++
            }

            // state.cartData.push(payload)
        },
        // DECREASE_CART(state,payload){
        //     console.log(payload);

        //     let target = state.cartData.find(item => item.id ===payload)
             
        //     if(target){
        //         target.count--
        //     }
        // }
    },
    actions: {
        ADD_CART(context,payload){
// 是为了学到如何在一个模块的store操作另一个store的mutation或action
        console.log('cart-action:',payload);
        context.commit('SET_CART',payload)

        context.commit('product/DECREASE_INVENTORY',payload.id,{root:true})
        },
        // REMOVE_CART(context,payload){
        //     console.log(payload);
        //     context.commit('cart/REMOVE_CART',payload)
        // }
    }, 
    getters: {
        // 总价计算
        total(state){
            return (state.cartData.reduce((total,item)=>
            { 
                return total += item.price * item.count
            },0)).toFixed(2)
        }
    },
}